package cn.sdack.go.users.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.AuditorAware;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.jwt.Jwt;

import java.util.Map;
import java.util.Optional;

/**
 * @author sdack
 * @date 2024/1/10
 */
@Configuration
@EnableJpaAuditing
public class JpaAuditingConfig {

    @Bean
    public AuditorAware<String> auditorProvider() {
        return () -> {
            try {
                Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
                Jwt principal = (Jwt) authentication.getPrincipal();
                Map<String, Object> claims = principal.getClaims();
                String name = String.valueOf(claims.get("sub"));
                return Optional.ofNullable(name);
            }catch (Exception e) {
                return Optional.ofNullable("");
            }
        };
    }

}
